﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Json2Excel
{
    /// <summary>
    /// 一个*.csv文件。
    /// </summary>
    public class CSVFile
    {
        private List<CSVColumn> columns = new List<CSVColumn>();
        public IList<CSVColumn> Columns { get { return this.columns; } }

        public void AddRow(params string[] columnData)
        {
            if (columnData.Length != columns.Count)
            {
                throw new ArgumentException();
            }

            for (int i = 0; i < columnData.Length; i++)
            {
                columns[i].Data.Add(columnData[i]);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fullname"></param>
        public void Save(string fullname)
        {
            if (!fullname.ToLower().EndsWith(".csv"))
            {
                fullname = fullname + ".csv";
            }

            using (var sw = new StreamWriter(fullname, false))
            {
                bool updated = true;
                for (int row = 0; updated; row++)
                {
                    updated = false;
                    for (int i = 0; i < columns.Count; i++)
                    {
                        var column = columns[i];
                        if (row < column.Data.Count)
                        {
                            sw.Write(column.Data[row]);
                            sw.Write(",");
                            updated = true;
                        }
                        else
                        {
                            sw.Write(string.Empty);
                            sw.Write(",");
                        }
                    }
                }
            }
        }
    }
}
